const { Node } = require("./SingleList");
const { CirSingleList } = require("./CirSingleList");
//双向链表
class DbList extends CirSingleList {
  constructor() {
    super();
  }
  // 在item后添加newElement
  insert(item, newElement) {
    let newNode = new Node(newElement);
    let itemNode = this.find(item);
    // 如果itemNode.next有值，则说明是往中间插入值
    if (itemNode.next) {
      newNode.next = itemNode.next;
      itemNode.next.prev = newNode;
      itemNode.next = newNode;
      newNode.prev = itemNode;
    } else {
      itemNode.next = newNode;
      newNode.prev = itemNode;
    }
    this.size++;
  }

  // 从双向链表中移除item节点
  remove(item) {
    let curNode = this.find(item);
    // 删除头节点
    if (item === "head") {
      this.head.next = null;
      this.head.prev = null;
      this.size = 0;
      return;
    }
    if (curNode) {
      // 没有next节点，说明是尾节点
      if (!curNode.next) {
        curNode.prev.next = null;
      } else {
        curNode.next.prev = curNode.prev;
        curNode.prev.next = curNode.next;
      }
      curNode = null;
      this.size--;
    }
  }

  display() {
    let description = "head";
    let currNode = this.head;
    let lastNode = this.findLast();
    // 判断节点是否到了尾节点
    while (currNode !== lastNode) {
      currNode = currNode.next;
      description += `<->${currNode.element}`;
    }

    console.log(description);
  }

  // 反向遍历
  reverseDisplay() {
    let description = "";
    let currNode = this.findLast();
    while (currNode.element !== "head") {
      description += `${currNode.element}<->`;
      currNode = currNode.prev;
    }
    description += 'head';
    console.log(description);
  }

  // 在尾部添加数据
  append(element) {
    let lastNode = this.findLast();
    let newNode = new Node(element);
    lastNode.next = newNode;
    newNode.prev = lastNode;
    this.size++;
  }
}

/* let test = new DbList();
test.insert("head", 1);
test.display(); // head->1

test.insert(1, 2);
test.insert(2, 3);
test.insert(3, 4);
test.append(8);
test.display(); // head->1->2

// test.insert(1, 1.5);
// test.display(); // head->1->1.5->2
// 删除最后一个节点
test.remove(4);
test.reverseDisplay(); // head->1->2->3 */

// // 删除中间的节点
// test.remove(2);
// test.display(); // head->1->3

// // 清空链表
// test.remove("head");
// test.display(); // head

module.exports = { DbList };
